//  [9/16/2013 OMEGA] created

#include <QtWidgets/QWidget>
#include <QtWidgets/QListWidgetItem>
#include "DuelAssEDualColumnSelectView.h"

DAssEDualColumnSelectView::DAssEDualColumnSelectView( QWidget* parent /*= 0*/ ) :
	QWidget(parent)
{
	ui.setupUi(this);
	ui.leftList->setSelectionMode(QAbstractItemView::MultiSelection);
	ui.rightList->setSelectionMode(QAbstractItemView::MultiSelection);
	ui.leftList->setItemDelegate(&mItemDelegate);
	ui.rightList->setItemDelegate(&mItemDelegate);
	connect(ui.selectButton, SIGNAL(clicked()), this, SLOT(onSelectButtonClicked()));
	connect(ui.unselectButton, SIGNAL(clicked()), this, SLOT(onUnselectButtonClicked()));
}

void DAssEDualColumnSelectView::setHeaderLabel( const QString& left, const QString& right )
{
	ui.leftLabel->setText(left);
	ui.rightLabel->setText(right);
}

void DAssEDualColumnSelectView::setItems( const QStringList& leftItms, const QStringList& rightItms )
{
	QStringList tmpLeft = leftItms;
	QStringList tmpRight = rightItms;
	foreach(const QString& rstr, tmpRight)
	{
		QStringList::iterator i, iend = tmpLeft.end();
		for(i = tmpLeft.begin(); i != iend; ++i)
		{
			if((*i) == rstr)
			{
				tmpLeft.erase(i);
				break;
			}
		}
	}
	ui.leftList->clear();
	ui.rightList->clear();
	mLeftItems = tmpLeft;
	mRightItems = tmpRight;
	ui.leftList->insertItems(0, tmpLeft);
	ui.rightList->insertItems(0, tmpRight);
}

void DAssEDualColumnSelectView::onSelectButtonClicked()
{
	QList<QListWidgetItem*> idxList = ui.leftList->selectedItems();
	foreach(QListWidgetItem* idx, idxList)
	{
		QString val = idx->data(Qt::EditRole).toString();
		mRightItems.push_back(val);
		ui.rightList->addItem(val);
	}
	for (int i = 0; i < mLeftItems.size(); ++i)
	{
		for (int j = 0; j < idxList.size(); ++j)
		{
			const QString& val = idxList.at(j)->data(Qt::EditRole).toString();
			if (val == mLeftItems.at(i))
			{
				idxList.takeAt(j);
				mLeftItems.takeAt(i);
				--i; // reset item;
				break;
			}
		}
	}
	ui.leftList->clear();
	ui.leftList->insertItems(0, mLeftItems);

}

void DAssEDualColumnSelectView::onUnselectButtonClicked()
{
	QList<QListWidgetItem*> idxList = ui.rightList->selectedItems();
	foreach(QListWidgetItem* idx, idxList)
	{
		QString val = idx->data(Qt::EditRole).toString();
		mLeftItems.push_back(val);
		ui.leftList->addItem(val);
	}
	for (int i = 0; i < mRightItems.size(); ++i)
	{
		for (int j = 0; j < idxList.size(); ++j)
		{
			const QString& val = idxList.at(j)->data(Qt::EditRole).toString();
			if (val == mRightItems.at(i))
			{
				idxList.takeAt(j);
				mRightItems.takeAt(i);
				--i;
				break;
			}
		}
	}
	ui.rightList->clear();
	ui.rightList->insertItems(0, mRightItems);
}
